package com.xianyuwangyou.taizhangdengji

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import java.io.File
import kotlin.math.cos
import kotlin.math.sin
import com.xianyuwangyou.taizhangdengji.ui.theme.TaizhangdengjiTheme
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.ui.res.painterResource

import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter

import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.compose.ui.layout.ContentScale
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.togetherWith
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.updateTransition
import coil.compose.AsyncImage
import coil.request.ImageRequest
import kotlinx.coroutines.launch
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
// 添加uCrop相关的导入
import com.yalantis.ucrop.UCrop
// 添加WebDAV相关导入
import androidx.compose.material3.AlertDialog
import androidx.compose.ui.text.input.PasswordVisualTransformation

class MainActivity : ComponentActivity() {
    // 存储权限请求启动器
    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val writePermissionGranted = permissions[android.Manifest.permission.WRITE_EXTERNAL_STORAGE] ?: false
        val readPermissionGranted = permissions[android.Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
        
        if (writePermissionGranted && readPermissionGranted) {
            // 权限获取成功，初始化应用数据
            initializeApp()
        } else {
            // 权限获取失败，显示提示信息
            Toast.makeText(this, "存储权限被拒绝，数据可能无法持久保存", Toast.LENGTH_LONG).show()
            // 仍然初始化应用数据
            initializeApp()
        }
    }
    
    // 添加数据更新时间戳，用于触发Compose重组
    private var dataUpdateTimestamp = mutableStateOf(System.currentTimeMillis())
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        // 检查并请求存储权限
        checkAndRequestStoragePermission()
    }
    
    private fun checkAndRequestStoragePermission() {
        val writePermission = ContextCompat.checkSelfPermission(
            this, 
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        val readPermission = ContextCompat.checkSelfPermission(
            this, 
            android.Manifest.permission.READ_EXTERNAL_STORAGE
        )
        
        if (writePermission == PackageManager.PERMISSION_GRANTED && 
            readPermission == PackageManager.PERMISSION_GRANTED) {
            // 已有权限，直接初始化应用
            initializeApp()
        } else {
            // 请求权限
            requestPermissionLauncher.launch(
                arrayOf(
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE
                )
            )
        }
    }
    
    private fun initializeApp() {
        // 初始化应用数据
        val appInitializer = AppInitializer()
        appInitializer.initializeAppData(this)
        
        // 初始化并加载数据
        val dataManager = AccountDataManager.getInstance()
        dataManager.loadAccountData(this) // 使用改进的加载方法
        
        // 初始化并加载配置数据
        val configDataManager = ConfigDataManager.getInstance()
        configDataManager.loadConfigData(this)
        
        setContent {
            TaizhangdengjiTheme {
                var currentPage by remember { mutableStateOf("home") }
                var totalRecords by remember { mutableIntStateOf(dataManager.getAccountRecords().size) }
                var recordToEdit by remember { mutableStateOf<AccountRecord?>(null) }
                // 添加数据更新时间戳状态
                var dataTimestamp by remember { mutableStateOf(System.currentTimeMillis()) }
                // 添加退出提示状态
                var showExitToast by remember { mutableStateOf(false) }
                
                // 注册广播接收器以监听数据变更
                DisposableEffect(Unit) {
                    val receiver = object : android.content.BroadcastReceiver() {
                        override fun onReceive(context: Context?, intent: Intent?) {
                            if (intent?.action == "com.xianyuwangyou.taizhangdengji.DATA_CHANGED") {
                                // 刷新数据
                                dataManager.loadAccountData(this@MainActivity)
                                // 更新记录数
                                totalRecords = dataManager.getAccountRecords().size
                                // 更新时间戳以触发重组
                                dataTimestamp = System.currentTimeMillis()
                            }
                        }
                    }
                    
                    val filter = IntentFilter("com.xianyuwangyou.taizhangdengji.DATA_CHANGED")
                    ContextCompat.registerReceiver(this@MainActivity, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
                    
                    onDispose {
                        this@MainActivity.unregisterReceiver(receiver)
                    }
                }
                
                // 当页面切换时刷新数据
                LaunchedEffect(currentPage) {
                    if (currentPage == "home") {
                        dataManager.loadAccountData(this@MainActivity)
                        totalRecords = dataManager.getAccountRecords().size
                        // 更新dataTimestamp以触发重组
                        dataTimestamp = System.currentTimeMillis()
                    }
                }
                
                // 处理自动隐藏退出提示
                LaunchedEffect(showExitToast) {
                    if (showExitToast) {
                        // 几秒后自动隐藏提示（3秒）
                        kotlinx.coroutines.delay(3000)
                        showExitToast = false
                    }
                }
                
                // 处理返回键事件
                val backDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
                val backCallback = remember {
                    object : OnBackPressedCallback(true) {
                        override fun handleOnBackPressed() {
                            when (currentPage) {
                                "home" -> {
                                    // 在主页时提示用户再次点击返回键退出应用
                                    if (showExitToast) {
                                        // 如果已经显示提示，则退出应用
                                        finish()
                                    } else {
                                        // 显示提示
                                        showExitToast = true
                                    }
                                }
                                "entry", "edit" -> {
                                    // 在录入或编辑页面时返回主页
                                    currentPage = "home"
                                }
                                "marketerManagement" -> {
                                    // 在营销人员管理页面时返回主页
                                    currentPage = "home"
                                }
                                "productManagement" -> {
                                    // 在产品管理页面时返回主页
                                    currentPage = "home"
                                }
                                "backgroundManagement" -> {
                                    // 在背景图管理页面时返回主页
                                    currentPage = "home"
                                }
                                else -> {
                                    // 默认情况返回主页
                                    currentPage = "home"
                                }
                            }
                        }
                    }
                }
                
                DisposableEffect(backDispatcher) {
                    backDispatcher?.addCallback(backCallback)
                    onDispose {
                        backCallback.remove()
                    }
                }
                
                // 使用AnimatedContent为页面切换添加动画效果
                AnimatedContent(
                    targetState = currentPage,
                    transitionSpec = {
                        // 根据页面切换方向设置不同的动画
                        when {
                            // 主页到台账登记页面（从下往上覆盖滑入）
                            targetState == "entry" && initialState == "home" -> {
                                slideInVertically(
                                    animationSpec = tween(300),
                                    initialOffsetY = { fullHeight: Int -> fullHeight }
                                ) togetherWith fadeOut(
                                    animationSpec = tween(300)
                                )
                            }
                            // 台账登记页面到主页（从上往下覆盖滑出）
                            targetState == "home" && initialState == "entry" -> {
                                fadeIn(
                                    animationSpec = tween(300)
                                ) togetherWith slideOutVertically(
                                    animationSpec = tween(300),
                                    targetOffsetY = { fullHeight: Int -> fullHeight }
                                )
                            }
                            // 主页到修改台账页面（从下往上覆盖滑入）
                            targetState == "edit" && initialState == "home" -> {
                                slideInVertically(
                                    animationSpec = tween(300),
                                    initialOffsetY = { fullHeight: Int -> fullHeight }
                                ) togetherWith fadeOut(
                                    animationSpec = tween(300)
                                )
                            }
                            // 修改台账页面到主页（从上往下覆盖滑出）
                            targetState == "home" && initialState == "edit" -> {
                                fadeIn(
                                    animationSpec = tween(300)
                                ) togetherWith slideOutVertically(
                                    animationSpec = tween(300),
                                    targetOffsetY = { fullHeight: Int -> fullHeight }
                                )
                            }
                            // 主页到其他页面（向右滑入，向左滑出）
                            targetState != "home" && targetState != "entry" && targetState != "edit" && initialState == "home" -> {
                                slideInHorizontally(
                                    animationSpec = tween(300),
                                    initialOffsetX = { fullWidth: Int -> fullWidth }
                                ) + fadeIn(
                                    animationSpec = tween(300)
                                ) togetherWith slideOutHorizontally(
                                    animationSpec = tween(300),
                                    targetOffsetX = { fullWidth: Int -> -fullWidth }
                                ) + fadeOut(
                                    animationSpec = tween(300)
                                )
                            }
                            // 其他页面到主页（向左滑入，向右滑出）
                            targetState == "home" && initialState != "home" && initialState != "entry" && initialState != "edit" -> {
                                slideInHorizontally(
                                    animationSpec = tween(300),
                                    initialOffsetX = { fullWidth: Int -> -fullWidth }
                                ) + fadeIn(
                                    animationSpec = tween(300)
                                ) togetherWith slideOutHorizontally(
                                    animationSpec = tween(300),
                                    targetOffsetX = { fullWidth: Int -> fullWidth }
                                ) + fadeOut(
                                    animationSpec = tween(300)
                                )
                            }
                            // 其他页面之间切换（淡入淡出）
                            else -> {
                                fadeIn(
                                    animationSpec = tween(300)
                                ) togetherWith fadeOut(
                                    animationSpec = tween(300)
                                )
                            }
                        }
                    },
                    label = "页面切换动画"
                ) { targetPage ->
                    when (targetPage) {
                        "home" -> DateListScreen(
                            totalRecords = totalRecords,
                            onAddClick = { currentPage = "entry" },
                            onEdit = { record -> 
                                recordToEdit = record
                                currentPage = "edit"
                            },
                            onDelete = { recordId ->
                                dataManager.deleteAccountRecordAndSave(recordId, this@MainActivity)
                                // 刷新数据
                                dataManager.loadAccountData(this@MainActivity)
                                totalRecords = dataManager.getAccountRecords().size
                            },
                            onNavigateToMarketerManagement = { currentPage = "marketerManagement" },
                            onNavigateToProductManagement = { currentPage = "productManagement" },
                            onNavigateToBackgroundManagement = { currentPage = "backgroundManagement" }
                        )
                        "entry" -> AccountEntryScreen(
                            onNavigateBack = { 
                                currentPage = "home"
                            }
                        )
                        "edit" -> {
                            val record = recordToEdit
                            if (record != null) {
                                AccountEditScreen(
                                    record = record,
                                    onNavigateBack = { 
                                        currentPage = "home"
                                    }
                                )
                            } else {
                                // 如果没有要编辑的记录，返回主页
                                currentPage = "home"
                            }
                        }
                        "marketerManagement" -> MarketerManagementScreen(
                            onNavigateBack = { currentPage = "home" }
                        )
                        "productManagement" -> ProductManagementScreen(
                            onNavigateBack = { currentPage = "home" }
                        )
                        "backgroundManagement" -> BackgroundImageManagementScreen(
                            onNavigateBack = { currentPage = "home" }
                        )
                    }
                }
                
                // 显示退出提示Toast（放在AnimatedContent之后确保显示在最上层）
                if (showExitToast) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .zIndex(100f), // 确保提示显示在最上层
                        contentAlignment = Alignment.BottomCenter
                    ) {
                        Card(
                            modifier = Modifier
                                .padding(8.dp)
                                .padding(bottom = 10.dp), // 增加距离屏幕底部的距离2.dp（原来8.dp基础上增加2.dp）
                            colors = CardDefaults.cardColors(
                                containerColor = Color.Black.copy(alpha = 0.6f) // 降低透明度使背景不那么显眼
                            )
                        ) {
                            Text(
                                text = "再按一次退出应用",
                                color = Color.White,
                                fontSize = 14.sp, // 减小文字大小
                                modifier = Modifier
                                    .padding(4.dp), // 减小内边距为4.dp
                                textAlign = TextAlign.Center
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun DateListScreen(
    totalRecords: Int,
    onAddClick: () -> Unit,
    onEdit: (AccountRecord) -> Unit,
    onDelete: (Int) -> Unit,
    onNavigateToMarketerManagement: () -> Unit,
    onNavigateToProductManagement: () -> Unit,
    onNavigateToBackgroundManagement: () -> Unit
) {
    val context = LocalContext.current
    val dataManager = AccountDataManager.getInstance()
    val scope = rememberCoroutineScope()
    
    var dates by remember { mutableStateOf<List<String>>(emptyList()) }
    var recordsMap by remember { mutableStateOf<Map<String, List<AccountRecord>>>(emptyMap()) }
    var showManagementMenu by remember { mutableStateOf(false) }
    var showExportResultDialog by remember { mutableStateOf(false) }
    var showExportConfirmDialog by remember { mutableStateOf(false) }
    var exportResultMessage by remember { mutableStateOf("") }
    
    // 计算当前页面实际显示的记录数
    var displayedRecordsCount by remember { mutableStateOf(0) }
    
    // 注册文件选择器用于导入功能
    val importFilePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        if (uri != null) {
            // 在后台线程中处理文件导入
            Thread {
                try {
                    val result = importLedgerData(context, uri)
                    (context as android.app.Activity).runOnUiThread {
                        exportResultMessage = result
                        showExportResultDialog = true
                        
                        // 如果导入成功，刷新数据
                        if (result.startsWith("成功导入")) {
                            // 发送数据变更广播
                            val intent = Intent("com.xianyuwangyou.taizhangdengji.DATA_CHANGED")
                            intent.setPackage(context.packageName)
                            context.sendBroadcast(intent)
                            
                            // 重新加载数据
                            dates = dataManager.getAllDates()
                            recordsMap = dates.associateWith { date -> dataManager.getRecordsByDate(date) }
                        }
                    }
                } catch (e: Exception) {
                    (context as android.app.Activity).runOnUiThread {
                        exportResultMessage = "导入失败: ${e.message}"
                        showExportResultDialog = true
                    }
                }
            }.start()
        }
    }
    
    // 注册目录选择器用于导出功能
    val exportDirectoryPickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.OpenDocumentTree()
    ) { uri: Uri? ->
        if (uri != null) {
            // 获取选择的目录路径
            val directoryPath = getPathFromUri(context, uri)
            if (directoryPath != null) {
                // 在后台线程中处理文件导出
                scope.launch {
                    exportLedgerData(context, directoryPath) { success, message ->
                        exportResultMessage = message
                        showExportResultDialog = true
                    }
                }
            } else {
                exportResultMessage = "无法获取所选目录路径"
                showExportResultDialog = true
            }
        }
    }
    
    // 使用dataTimestamp作为状态来触发重组
    val dataTimestamp by remember { mutableStateOf(System.currentTimeMillis()) }
    
    // 当总记录数变化或数据更新时重新加载数据
    LaunchedEffect(totalRecords, dataTimestamp) {
        dates = dataManager.getAllDates()
        recordsMap = dates.associateWith { date -> dataManager.getRecordsByDate(date) }
        // 计算当前显示的记录总数
        displayedRecordsCount = recordsMap.values.sumOf { it.size }
    }
    
    // 添加一个单独的LaunchedEffect来监听数据更新
    LaunchedEffect(dataTimestamp) {
        dates = dataManager.getAllDates()
        recordsMap = dates.associateWith { date -> dataManager.getRecordsByDate(date) }
        // 计算当前显示的记录总数
        displayedRecordsCount = recordsMap.values.sumOf { it.size }
    }

    Box(modifier = Modifier.fillMaxSize().background(Color.LightGray)) {
        // 导出结果对话框
        if (showExportResultDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showExportResultDialog = false },
                title = { Text("操作结果") },
                text = { Text(exportResultMessage) },
                confirmButton = {
                    TextButton(onClick = { showExportResultDialog = false }) {
                        Text("确定",color = Color(0xFF019883))
                    }
                }
            )
        }
        
        // 导出确认对话框
        if (showExportConfirmDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showExportConfirmDialog = false },
                title = { Text("确认导出") },
                text = { 
                    Column {
                        Text("确定要导出台账数据吗？")
                        Text(
                            text = "请选择导出文件保存的位置",
                            style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                            color = Color(0xFF019883),
                            modifier = Modifier.padding(top = 8.dp)
                        )
                    }
                },
                confirmButton = {
                    TextButton(onClick = {
                        // 确认导出，打开目录选择器
                        showExportConfirmDialog = false
                        exportDirectoryPickerLauncher.launch(null)
                    }) {
                        Text("选择路径", color = Color(0xFF019883))
                    }
                },
                dismissButton = {
                    TextButton(onClick = {
                        // 取消导出
                        showExportConfirmDialog = false
                    }) {
                        Text("取消", color = Color(0xFF019883))
                    }
                }
            )
        }
        
        // 顶部图片区域，平铺满整个页面上方
        ImageHeader(
            modifier = Modifier
                .fillMaxWidth()
                .height(220.dp) // 原来是200.dp，增加1/10即20.dp，现在是220.dp
                .zIndex(1f), // 置于最顶层
            onSettingsClick = {
                // 显示管理选项菜单
                showManagementMenu = true
            }
        )

        // 在头图下方显示记录数的悬浮卡片
        Card(
            modifier = Modifier
                .align(Alignment.TopStart) // 居左展示
                .offset(y = 170.dp) // 头图高度220.dp，卡片高度40.dp，所以偏移170.dp使其部分重叠
                .zIndex(2f) // 确保在最顶层
                .padding(start = 16.dp),
            colors = CardDefaults.cardColors(
                containerColor = Color.White.copy(alpha = 0.8f) // 绿色背景
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Box(
                modifier = Modifier
                    .height(40.dp)
                    .padding(horizontal = 12.dp), // 左右内边距，确保文字不会紧贴边缘
                contentAlignment = Alignment.CenterStart // 内容居左对齐
            ) {
                Text(
                    text = "记录数: $displayedRecordsCount 条",
                    color = Color(0xFF019883),
                    fontSize = 14.sp, // 字体大小
                    fontWeight = FontWeight.Black
                )
            }
        }

        // 设置页面
        if (showManagementMenu) {
            SettingsScreen(
                onDismiss = { showManagementMenu = false },
                onNavigateToMarketerManagement = onNavigateToMarketerManagement,
                onNavigateToProductManagement = onNavigateToProductManagement,
                onImportData = {
                    showManagementMenu = false
                    // 使用"*/*"提高文件选择器兼容性
                    importFilePickerLauncher.launch("*/*")
                },
                onExportData = {
                    showManagementMenu = false
                    // 显示导出确认对话框
                    showExportConfirmDialog = true
                },
                onNavigateToBackgroundManagement = onNavigateToBackgroundManagement
            )
        }

        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 220.dp) // 头图高度(220.dp)
                .padding(WindowInsets.navigationBars.asPaddingValues()), // 使用WindowInsets处理导航栏内边距
            userScrollEnabled = true
        ) {
            items(dates.size) { index ->
                val date = dates[index]
                val records = recordsMap[date] ?: emptyList()
                DateItem(
                    date = date,
                    records = records,
                    modifier = if (index == 0) Modifier.padding(top = 4.dp) else Modifier, // 第一个卡片上边距为4.dp
                    onEdit = onEdit,
                    onDelete = onDelete
                )
            }
        }

        // 悬浮按钮，置于最顶层
        FloatingActionButton(
            onClick = onAddClick,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
                .padding(bottom = 32.dp) // 增加距离屏幕底部的距离
                .zIndex(2f) // 确保在最顶层
                .windowInsetsPadding(WindowInsets.navigationBars) // 使用WindowInsets处理导航栏内边距
                .size(56.dp), // 设置固定大小，确保是正圆形
            containerColor = Color.White
        ) {
            Icon(
                imageVector = Icons.Filled.Add,
                contentDescription = "添加台账记录",
                tint = Color(0xFF019883) // 设置图标为黑色以在白色背景上清晰显示
            )
        }

    }
}

// 设置页面组件
@Composable
fun SettingsScreen(
    onDismiss: () -> Unit,
    onNavigateToMarketerManagement: () -> Unit,
    onNavigateToProductManagement: () -> Unit,
    onImportData: () -> Unit,
    onExportData: () -> Unit,
    onNavigateToBackgroundManagement: () -> Unit
) {
    // 添加WebDAV配置状态
    var showWebDAVDialog by remember { mutableStateOf(false) }
    var showWebDAVResultDialog by remember { mutableStateOf(false) }
    var webDAVResultMessage by remember { mutableStateOf("") }
    
    // 添加FTP配置状态
    var showFTPDialog by remember { mutableStateOf(false) }
    var showFTPResultDialog by remember { mutableStateOf(false) }
    var ftpResultMessage by remember { mutableStateOf("") }
    
    var isSyncing by remember { mutableStateOf(false) }
    
    val context = LocalContext.current
    
    val transitionState = remember { mutableStateOf(false) }
    val transition = updateTransition(transitionState.value, label = "设置页面过渡动画")
    
    // 初始化时触发动画
    LaunchedEffect(Unit) {
        transitionState.value = true
    }
    
    val slideOffset by transition.animateFloat(
        transitionSpec = {
            tween(durationMillis = 300)
        },
        label = "slideOffset"
    ) { state: Boolean ->
        if (state) 0f else -1f
    }
    
    // 添加遮罩层透明度动画
    val maskAlpha by transition.animateFloat(
        transitionSpec = {
            tween(durationMillis = 300)
        },
        label = "maskAlpha"
    ) { state: Boolean ->
        if (state) 0.5f else 0f
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .zIndex(10f)
    ) {
        // 半透明遮罩层，带有淡入淡出动画
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = maskAlpha))
                .clickable {
                    transitionState.value = false
                    // 延迟调用 onDismiss，等待动画完成
                    kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                        kotlinx.coroutines.delay(300)
                        onDismiss()
                    }
                }
        )
        
        // 设置页面内容
        Box(
            modifier = Modifier
                .fillMaxWidth(0.66f) // 占据屏幕2/3宽度
                .fillMaxHeight()
                .offset(x = with(LocalDensity.current) {
                    (slideOffset * 0.66f * LocalConfiguration.current.screenWidthDp).dp
                })
                .background(androidx.compose.material3.MaterialTheme.colorScheme.surface)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxHeight()
                    .padding(16.dp),
                horizontalAlignment = Alignment.Start // 内容居中靠左展示
            ) {
                // 顶部标题栏（已移除返回按钮和设置字样）
                
                // 设置选项标题
                Text(
                    text = "选项",
                    style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Black,
                    fontSize = 20.sp,
                    modifier = Modifier
                        .padding(top = 200.dp)
                        .padding(vertical = 8.dp)
                )
                
                HorizontalDivider()
                
                SettingItem(
                    text = "营销人管理",
                    onClick = {
                        transitionState.value = false
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            kotlinx.coroutines.delay(300)
                            onNavigateToMarketerManagement()
                        }
                    }
                )
                
                SettingItem(
                    text = "产品管理",
                    onClick = {
                        transitionState.value = false
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            kotlinx.coroutines.delay(300)
                            onNavigateToProductManagement()
                        }
                    }
                )
                
                SettingItem(
                    text = "背景图管理",
                    onClick = {
                        transitionState.value = false
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            kotlinx.coroutines.delay(300)
                            onNavigateToBackgroundManagement()
                        }
                    }
                )
                
                HorizontalDivider()
                
                SettingItem(
                    text = "导入数据",
                    onClick = {
                        transitionState.value = false
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            kotlinx.coroutines.delay(300)
                            onImportData()
                        }
                    }
                )
                
                SettingItem(
                    text = "导出数据",
                    onClick = {
                        transitionState.value = false
                        kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Main).launch {
                            kotlinx.coroutines.delay(300)
                            onExportData()
                        }
                    }
                )
                
                HorizontalDivider()
                
                SettingItem(
                    text = "WebDAV同步",
                    onClick = {
                        showWebDAVDialog = true
                    }
                )
                
                SettingItem(
                    text = "FTP同步",
                    onClick = {
                        showFTPDialog = true
                    }
                )
            }
        }
        
        // WebDAV配置对话框
        if (showWebDAVDialog) {
            WebDAVConfigDialog(
                onDismiss = { showWebDAVDialog = false },
                onConfirm = { server: String, username: String, password: String, remotePath: String ->
                    showWebDAVDialog = false
                    isSyncing = true
                    
                    val webDAVConfig = WebDAVSyncManager.WebDAVConfig(server, username, password, remotePath)
                    val syncManager = WebDAVSyncManager.getInstance()
                    
                    syncManager.syncWithWebDAV(context, webDAVConfig, object : WebDAVSyncManager.SyncCallback {
                        override fun onSuccess(message: String) {
                            (context as android.app.Activity).runOnUiThread {
                                isSyncing = false
                                webDAVResultMessage = message
                                showWebDAVResultDialog = true
                                
                                // 发送数据变更广播以刷新UI
                                val intent = android.content.Intent("com.xianyuwangyou.taizhangdengji.DATA_CHANGED")
                                intent.setPackage(context.packageName)
                                context.sendBroadcast(intent)
                            }
                        }
                        
                        override fun onError(error: String) {
                            (context as android.app.Activity).runOnUiThread {
                                isSyncing = false
                                webDAVResultMessage = "同步失败: $error"
                                showWebDAVResultDialog = true
                            }
                        }
                    })
                }
            )
        }
        
        // FTP配置对话框
        if (showFTPDialog) {
            FTPConfigDialog(
                onDismiss = { showFTPDialog = false },
                onConfirm = { server: String, port: Int, username: String, password: String, remotePath: String ->
                    showFTPDialog = false
                    isSyncing = true
                    
                    val ftpConfig = FTPSyncManager.FTPConfig(server, port, username, password, remotePath)
                    val syncManager = FTPSyncManager.getInstance()
                    
                    syncManager.syncWithFTP(context, ftpConfig, object : FTPSyncManager.SyncCallback {
                        override fun onSuccess(message: String) {
                            (context as android.app.Activity).runOnUiThread {
                                isSyncing = false
                                ftpResultMessage = message
                                showFTPResultDialog = true
                                
                                // 发送数据变更广播以刷新UI
                                val intent = android.content.Intent("com.xianyuwangyou.taizhangdengji.DATA_CHANGED")
                                intent.setPackage(context.packageName)
                                context.sendBroadcast(intent)
                            }
                        }
                        
                        override fun onError(error: String) {
                            (context as android.app.Activity).runOnUiThread {
                                isSyncing = false
                                ftpResultMessage = "同步失败: $error"
                                showFTPResultDialog = true
                            }
                        }
                    })
                }
            )
        }
        
        // WebDAV同步结果对话框
        if (showWebDAVResultDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showWebDAVResultDialog = false },
                title = { Text("WebDAV同步") },
                text = { Text(webDAVResultMessage) },
                confirmButton = {
                    TextButton(onClick = { showWebDAVResultDialog = false }) {
                        Text("确定", color = Color(0xFF019883))
                    }
                }
            )
        }
        
        // FTP同步结果对话框
        if (showFTPResultDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showFTPResultDialog = false },
                title = { Text("FTP同步") },
                text = { Text(ftpResultMessage) },
                confirmButton = {
                    TextButton(onClick = { showFTPResultDialog = false }) {
                        Text("确定", color = Color(0xFF019883))
                    }
                }
            )
        }
        
        // 同步进度指示器
        if (isSyncing) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .zIndex(20f),
                contentAlignment = Alignment.Center
            ) {
                androidx.compose.material3.Card(
                    modifier = Modifier
                        .padding(16.dp)
                        .width(250.dp),
                    colors = androidx.compose.material3.CardDefaults.cardColors(
                        containerColor = androidx.compose.material3.MaterialTheme.colorScheme.surface
                    ),
                    elevation = androidx.compose.material3.CardDefaults.cardElevation(defaultElevation = 8.dp)
                ) {
                    Row(
                        modifier = Modifier
                            .padding(16.dp)
                            .fillMaxWidth(),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        androidx.compose.material3.CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = Color(0xFF019883)
                        )
                        Text(
                            text = "正在同步...",
                            modifier = Modifier.padding(start = 16.dp),
                            color = androidx.compose.material3.MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            }
        }
    }
}

// WebDAV配置对话框
@Composable
fun WebDAVConfigDialog(
    onDismiss: () -> Unit,
    onConfirm: (server: String, username: String, password: String, remotePath: String) -> Unit
) {
    var server by remember { mutableStateOf("") }
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var remotePath by remember { mutableStateOf("") }
    
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("WebDAV配置") },
        text = {
            Column {
                androidx.compose.material3.OutlinedTextField(
                    value = server,
                    onValueChange = { server = it },
                    label = { Text("服务器地址") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    label = { Text("用户名") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    label = { Text("密码") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = remotePath,
                    onValueChange = { remotePath = it },
                    label = { Text("远程路径(可选)") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Text(
                    text = "例如: https://your-nextcloud.com",
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                    color = Color.Gray,
                    modifier = Modifier.padding(top = 8.dp)
                )
            }
        },
        confirmButton = {
            androidx.compose.material3.TextButton(
                onClick = {
                    if (server.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()) {
                        onConfirm(server, username, password, remotePath)
                    }
                },
                enabled = server.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()
            ) {
                Text("同步")
            }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

// FTP配置对话框
@Composable
fun FTPConfigDialog(
    onDismiss: () -> Unit,
    onConfirm: (server: String, port: Int, username: String, password: String, remotePath: String) -> Unit
) {
    var server by remember { mutableStateOf("") }
    var port by remember { mutableStateOf("21") }
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var remotePath by remember { mutableStateOf("/") }
    
    androidx.compose.material3.AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("FTP配置") },
        text = {
            Column {
                androidx.compose.material3.OutlinedTextField(
                    value = server,
                    onValueChange = { server = it },
                    label = { Text("服务器地址") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = port,
                    onValueChange = { 
                        port = it
                        // 确保输入的是数字
                        if (it.isNotEmpty() && !it.all { char -> char.isDigit() }) {
                            port = it.filter { char -> char.isDigit() }
                        }
                    },
                    label = { Text("端口") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    label = { Text("用户名") },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    label = { Text("密码") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 8.dp)
                )
                
                androidx.compose.material3.OutlinedTextField(
                    value = remotePath,
                    onValueChange = { remotePath = it },
                    label = { Text("远程路径") },
                    modifier = Modifier.fillMaxWidth()
                )
                
                Text(
                    text = "例如: ftp.example.com",
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                    color = Color.Gray,
                    modifier = Modifier.padding(top = 8.dp)
                )
            }
        },
        confirmButton = {
            androidx.compose.material3.TextButton(
                onClick = {
                    if (server.isNotEmpty() && port.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()) {
                        val portNumber = port.toIntOrNull() ?: 21
                        onConfirm(server, portNumber, username, password, remotePath)
                    }
                },
                enabled = server.isNotEmpty() && port.isNotEmpty() && username.isNotEmpty() && password.isNotEmpty()
            ) {
                Text("同步")
            }
        },
        dismissButton = {
            androidx.compose.material3.TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

@Composable
fun SettingItem(
    text: String,
    onClick: () -> Unit
) {
    Text(
        text = text,
        style = MaterialTheme.typography.bodyLarge,
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 16.dp)
    )
}

// 管理菜单组件
@Composable
fun ManagementMenu(
    onDismiss: () -> Unit,
    onManageMarketers: () -> Unit,
    onManageProducts: () -> Unit,
    onImportData: () -> Unit, // 导入数据回调
    onExportData: () -> Unit, // 导出数据回调
    onManageBackground: () -> Unit // 背景图管理回调
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .zIndex(3f) // 确保在最顶层
            .clickable { onDismiss() } // 点击背景关闭菜单
    ) {
        Card(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .padding(top = 70.dp, end = 16.dp)
                .width(200.dp),
            elevation = CardDefaults.cardElevation(defaultElevation = 8.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                Text(
                    text = "管理选项",
                    style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                
                HorizontalDivider(
                    color = Color.LightGray,
                    modifier = Modifier.padding(vertical = 4.dp)
                )
                
                Text(
                    text = "营销人管理",
                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onDismiss()
                            onManageMarketers()
                        }
                        .padding(vertical = 12.dp)
                )
                
                Text(
                    text = "产品管理",
                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onDismiss()
                            onManageProducts()
                        }
                        .padding(vertical = 12.dp)
                )
                
                Text(
                    text = "导入台账",
                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onDismiss()
                            onImportData()
                        }
                        .padding(vertical = 12.dp)
                )
                
                Text(
                    text = "导出台账",
                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onDismiss()
                            onExportData()
                        }
                        .padding(vertical = 12.dp)
                )
                
                Text(
                    text = "背景图管理",
                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge,
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onDismiss()
                            onManageBackground()
                        }
                        .padding(vertical = 12.dp)
                )
            }
        }
    }
}

// 转盘菜单组件
@Composable
fun RadialMenu(
    onDismiss: () -> Unit,
    onMarketerManagementClick: () -> Unit,
    onProductManagementClick: () -> Unit,
    onDataExportClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .clickable { onDismiss() } // 点击背景关闭菜单
    ) {
        Box(
            modifier = Modifier
                .size(300.dp)
                .align(Alignment.Center)
        ) {
            // 转盘背景
            Canvas(modifier = Modifier.fillMaxSize()) {
                val radius = size.minDimension / 2
                val center = Offset(size.width / 2, size.height / 2)
                
                // 绘制转盘背景
                drawCircle(
                    color = Color.White,
                    radius = radius,
                    center = center
                )
                
                // 绘制边界
                drawCircle(
                    color = Color.LightGray,
                    radius = radius,
                    center = center,
                    style = Stroke(width = 4f)
                )
                
                // 绘制分割线
                for (i in 0 until 3) {
                    val angle = Math.toRadians((i * 120 + 60).toDouble()).toFloat()
                    val startX = center.x + (radius * 0.2f) * cos(angle)
                    val startY = center.y + (radius * 0.2f) * sin(angle)
                    val endX = center.x + radius * cos(angle)
                    val endY = center.y + radius * sin(angle)
                    
                    drawLine(
                        color = Color.LightGray,
                        start = Offset(startX, startY),
                        end = Offset(endX, endY),
                        strokeWidth = 2f
                    )
                }
            }
            
            // 菜单项
            RadialMenuItem(
                text = "营销人管理",
                angle = 300f, // 顶部
                onClick = onMarketerManagementClick
            )
            
            RadialMenuItem(
                text = "产品管理",
                angle = 60f, // 右侧
                onClick = onProductManagementClick
            )
            
            RadialMenuItem(
                text = "数据导出",
                angle = 180f, // 左侧
                onClick = onDataExportClick
            )
            
            // 中心关闭按钮
            IconButton(
                onClick = onDismiss,
                modifier = Modifier
                    .size(50.dp)
                    .align(Alignment.Center)
            ) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "关闭菜单",
                    tint = Color.Gray
                )
            }
        }
    }
}

// 转盘菜单项组件
@Composable
fun RadialMenuItem(
    text: String,
    angle: Float,
    onClick: () -> Unit
) {
    val radius = 100.dp
    val angleInRadians = Math.toRadians(angle.toDouble())
    val offsetX = (radius.value * cos(angleInRadians).toFloat()).dp
    val offsetY = (radius.value * sin(angleInRadians).toFloat()).dp
    
    Box(
        modifier = Modifier
            .size(80.dp)
            .offset(x = offsetX, y = offsetY)
            .clickable { onClick() },
        contentAlignment = Alignment.Center
    ) {
        Card(
            modifier = Modifier.fillMaxSize(),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
            colors = CardDefaults.cardColors(containerColor = Color.White)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = text,
                    textAlign = TextAlign.Center,
                    fontSize = 12.sp,
                    color = Color(0xFF1976D2)
                )
            }
        }
    }
}

@Composable
fun MenuOptionItem(
    text: String,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .size(120.dp) // 正方形卡片
            .padding(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White // 纯白背景
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .clickable { onClick() },
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = text,
                style = androidx.compose.material3.MaterialTheme.typography.bodyMedium,
                color = Color(0xFF1976D2), // 深蓝色文字
                textAlign = TextAlign.Center
            )
        }
    }
}

@Composable
fun ImageHeader(
    modifier: Modifier = Modifier,
    onSettingsClick: () -> Unit = {}
) {
    val context = LocalContext.current
    val backgroundImageManager = BackgroundImageManager.getInstance()
    // 检查背景图片是否存在，如果存在则使用背景图片URI，否则使用默认图片
    val backgroundImageUri = if (backgroundImageManager.isBackgroundImageExists(context)) {
        backgroundImageManager.getBackgroundImageUri(context)
    } else {
        "file:///android_asset/pic.png"
    }
    
    Box(modifier = modifier) {
        // 显示背景图片，如果没有设置则显示默认图片
        AsyncImage(
            model = ImageRequest.Builder(context)
                .data(backgroundImageUri)
                .crossfade(true)
                .build(),
            contentDescription = "顶部头图",
            contentScale = ContentScale.Crop, // 裁剪以填充整个区域
            modifier = Modifier.fillMaxSize()
        )
        
        // 添加设置按钮（菜单图标）
        IconButton(
            onClick = onSettingsClick,
            modifier = Modifier
                .align(Alignment.TopStart) // 改为左上角对齐
                .padding(start = 16.dp, top = 40.dp) // 左侧距离16dp，顶部距离增加到40dp
                .size(48.dp) // 增加按钮尺寸到48dp
                .zIndex(2f)
        ) {
            Icon(
                imageVector = Icons.Filled.Menu, // 改为菜单图标（三条横线）
                contentDescription = "设置",
                tint = Color(0xFF019883), // 纯白颜色
                modifier = Modifier.size(32.dp) // 增加图标尺寸到32dp
            )
        }
    }
}

@Composable
fun DateItem(
    date: String, 
    records: List<AccountRecord>,
    modifier: Modifier = Modifier,
    onEdit: (AccountRecord) -> Unit = {},
    onDelete: (Int) -> Unit = {}
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 4.dp, vertical = 2.dp), // 调整左右边距为4.dp，上下边距为2.dp
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = androidx.compose.material3.MaterialTheme.colorScheme.surface // 白色卡片
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 格式化日期显示
            val formattedDate = formatDisplayDate(date)
            Text(
                text = formattedDate,
                style = androidx.compose.material3.MaterialTheme.typography.titleMedium
            )
            
            // 显示该日期下的所有记录
            records.forEachIndexed { index, record ->
                RecordItem(
                    record = record, 
                    modifier = Modifier.padding(top = 8.dp),
                    onEdit = onEdit,
                    onDelete = onDelete
                )
            }
        }
    }
}

// 格式化日期显示的辅助函数
fun formatDisplayDate(dateStr: String): String {
    return try {
        // 解析输入的日期字符串 (yyyy-MM-dd)
        val inputFormat = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
        val date = inputFormat.parse(dateStr) ?: return dateStr
        
        // 获取当前日期和昨天、前天的日期
        val calendar = java.util.Calendar.getInstance()
        val today = calendar.time
        
        calendar.add(java.util.Calendar.DAY_OF_YEAR, -1)
        val yesterday = calendar.time
        
        calendar.add(java.util.Calendar.DAY_OF_YEAR, -1)
        val dayBeforeYesterday = calendar.time
        
        // 格式化星期
        val dayOfWeekFormat = java.text.SimpleDateFormat("EEEE", java.util.Locale.CHINESE)
        val dayOfWeek = dayOfWeekFormat.format(date).replace("星期", "周")
        
        // 检查是否是近三天
        val dateFormat = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
        when (dateFormat.format(date)) {
            dateFormat.format(today) -> "$dateStr $dayOfWeek 今天"
            dateFormat.format(yesterday) -> "$dateStr $dayOfWeek 昨天"
            dateFormat.format(dayBeforeYesterday) -> "$dateStr $dayOfWeek 前天"
            else -> "$dateStr $dayOfWeek"
        }
    } catch (e: Exception) {
        // 如果解析失败，返回原始日期字符串
        dateStr
    }
}

@Composable
fun RecordItem(
    record: AccountRecord,
    modifier: Modifier = Modifier,
    onEdit: (AccountRecord) -> Unit = {},
    onDelete: (Int) -> Unit = {}
) {
    // 每条记录展示为1行，点击后直接跳转到编辑页面
    Column(
        modifier = modifier
            .fillMaxWidth()
            .clickable {
                // 点击记录直接跳转到编辑页面
                onEdit(record)
            }
            .padding(4.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧：产品名称和备注
            Column(
                modifier = Modifier.weight(2f)
            ) {
                // 产品名称（加粗显示，较小字体）
                // 优先显示二级产品名称，如果没有则显示一级产品名称
                Text(
                    text = if (record.secondaryProduct.isNotEmpty()) record.secondaryProduct else record.product,
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall.copy(
                        fontWeight = FontWeight.Bold
                    )
                )
                
                // 备注信息（如果存在，更小字体）
                if (record.notes.isNotEmpty()) {
                    Text(
                        text = record.notes,
                        style = androidx.compose.material3.MaterialTheme.typography.bodySmall.copy(
                            fontSize = androidx.compose.material3.MaterialTheme.typography.labelSmall.fontSize
                        ),
                        color = Color.Gray,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            
            // 营销员（垂直居中）
            Text(
                text = record.marketer,
                style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                modifier = Modifier.weight(1f)
            )
            
            // 数量（垂直居中）- 减小宽度
            Text(
                text = record.amount.toString(),
                style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                modifier = Modifier.weight(0.8f) // 减小数量区域的宽度
            )
            
            // ID显示（垂直居中，灰色字体，分两行显示，居中对齐）- 增加宽度
            Column(
                modifier = Modifier.weight(1.2f), // 增加ID区域的宽度
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "id",
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                    color = Color.Gray,
                    modifier = Modifier.padding(bottom = 2.dp)
                )
                Text(
                    text = record.id.toString(),
                    style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                    color = Color.Gray
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun DateListPreview() {
    TaizhangdengjiTheme {
        DateListScreen(
            totalRecords = 45,
            onAddClick = {},
            onEdit = {},
            onDelete = {},
            onNavigateToMarketerManagement = {},
            onNavigateToProductManagement = {},
            onNavigateToBackgroundManagement = {}
        )
    }
}

@Composable
fun MarketerManagementScreen(
    onNavigateBack: () -> Unit
) {
    val context = LocalContext.current
    val configDataManager = ConfigDataManager.getInstance()
    var marketers by remember { mutableStateOf(configDataManager.getMarketers()) }
    var newMarketer by remember { mutableStateOf("") }
    var showAddDialog by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        marketers = configDataManager.getMarketers()
    }
    
    Box(modifier = Modifier.fillMaxSize().background(Color.LightGray)) { // 添加灰色背景
        Column(modifier = Modifier.fillMaxSize()) {
            // 顶部工具栏
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White)
                    .padding(8.dp)
                    .padding(top = 24.dp) // 增加与屏幕顶端的距离
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                    Text(
                        text = "营销人管理",
                        style = androidx.compose.material3.MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }
            
            // 营销人列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 8.dp),
                contentPadding = PaddingValues(top = 4.dp)
            ) {
                items(marketers) { marketer ->
                    MarketerItem(
                        marketer = marketer,
                        onDelete = {
                            configDataManager.removeMarketer(context, marketer)
                            marketers = configDataManager.getMarketers()
                        }
                    )
                }
            }
        }
        
        // 添加按钮，置于底部正中间
        FloatingActionButton(
            onClick = { showAddDialog = true },
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
                .padding(bottom = 32.dp), // 增加距离屏幕底部的距离
                containerColor = Color.White
        ) {
            Icon(
                imageVector = Icons.Filled.Add, 
                contentDescription = "添加营销人",
                tint = Color(0xFF019883) // 设置图标为黑色以在白色背景上清晰显示
            )
        }
        
        // 添加营销人对话框
        if (showAddDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showAddDialog = false },
                title = { Text("添加营销人") },
                text = {
                    OutlinedTextField(
                        value = newMarketer,
                        onValueChange = { newMarketer = it },
                        label = { Text("营销人姓名") },
                        modifier = Modifier.fillMaxWidth()
                    )
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            if (newMarketer.isNotBlank()) {
                                configDataManager.addMarketer(context, newMarketer)
                                marketers = configDataManager.getMarketers()
                                newMarketer = ""
                                showAddDialog = false
                            }
                        }
                    ) {
                        Text("添加", color = Color(0xFF019883))
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showAddDialog = false }) {
                        Text("取消", color = Color(0xFF019883))
                    }
                }
            )
        }
    }
}

@Composable
fun MarketerItem(
    marketer: String,
    onDelete: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White // 纯白背景
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp), // 缩小内边距
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = marketer,
                modifier = Modifier.weight(1f),
                style = androidx.compose.material3.MaterialTheme.typography.bodyLarge
            )
            IconButton(onClick = onDelete) {
                Icon(
                    imageVector = Icons.Filled.Delete,
                    contentDescription = "删除",
                    tint = Color.Red
                )
            }
        }
    }
}

@Composable
fun ProductManagementScreen(
    onNavigateBack: () -> Unit
) {
    val context = LocalContext.current
    val configDataManager = ConfigDataManager.getInstance()
    var products by remember { mutableStateOf(configDataManager.getProducts()) }
    var productsWithSecondaries by remember { mutableStateOf(configDataManager.getProductsWithSecondaries()) }
    var newProduct by remember { mutableStateOf("") }
    var newSecondaryProduct by remember { mutableStateOf("") }
    var showAddDialog by remember { mutableStateOf(false) }
    var showAddSecondaryDialog by remember { mutableStateOf(false) }
    var selectedProduct by remember { mutableStateOf("") }
    var expandedProducts by remember { mutableStateOf(setOf<String>()) }
    
    LaunchedEffect(Unit) {
        products = configDataManager.getProducts()
        productsWithSecondaries = configDataManager.getProductsWithSecondaries()
    }
    
    Box(modifier = Modifier.fillMaxSize().background(Color.LightGray)) { // 添加灰色背景
        Column(modifier = Modifier.fillMaxSize()) {
            // 顶部工具栏
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White)
                    .padding(8.dp)
                    .padding(top = 24.dp) // 增加与屏幕顶端的距离
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                    Text(
                        text = "产品管理",
                        style = androidx.compose.material3.MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }
            
            // 产品列表
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 8.dp),
                contentPadding = PaddingValues(top = 4.dp)
            ) {
                items(products.withIndex().toList()) { (index, product) ->
                    val isExpanded = expandedProducts.contains(product)
                    val secondaryProducts = configDataManager.getSecondaryProducts(product)
                    
                    Column {
                        // 一级产品项
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp),
                            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                            colors = CardDefaults.cardColors(
                                containerColor = Color.White // 纯白背景
                            )
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(12.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                // 展开/收起图标
                                IconButton(
                                    onClick = {
                                        expandedProducts = if (isExpanded) {
                                            expandedProducts - product
                                        } else {
                                            expandedProducts + product
                                        }
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Filled.ArrowDropDown,
                                        contentDescription = if (isExpanded) "收起" else "展开"
                                    )
                                }
                                
                                Text(
                                    text = product,
                                    modifier = Modifier.weight(1f),
                                    style = androidx.compose.material3.MaterialTheme.typography.bodyLarge
                                )
                                
                                // 向上移动按钮（仅当不是第一个产品时显示）
                                if (index > 0) {
                                    IconButton(
                                        onClick = {
                                            // 交换当前项与上一项的位置
                                            val currentProducts = products.toMutableList()
                                            val temp = currentProducts[index]
                                            currentProducts[index] = currentProducts[index - 1]
                                            currentProducts[index - 1] = temp
                                            
                                            // 更新产品列表
                                            products = currentProducts
                                            
                                            // 更新配置数据
                                            val productWithSecondaries = configDataManager.getProductsWithSecondaries().toMutableList()
                                            val tempProduct = productWithSecondaries[index]
                                            productWithSecondaries[index] = productWithSecondaries[index - 1]
                                            productWithSecondaries[index - 1] = tempProduct
                                            
                                            // 保存更新后的数据
                                            val updatedConfigData = ConfigData(
                                                configDataManager.getMarketers(),
                                                productWithSecondaries
                                            )
                                            configDataManager.updateConfigData(context, updatedConfigData)
                                        }
                                    ) {
                                        Image(
                                            painter = painterResource(id = R.drawable.arrowdropup),
                                            contentDescription = "向上移动",
                                            modifier = Modifier.size(24.dp),
                                            colorFilter = ColorFilter.tint(Color.Black)
                                        )
                                    }
                                }
                                
                                // 添加二级产品按钮
                                IconButton(
                                    onClick = {
                                        selectedProduct = product
                                        showAddSecondaryDialog = true
                                    }
                                ) {
                                    Icon(
                                        imageVector = Icons.Filled.Add,
                                        contentDescription = "添加二级产品"
                                    )
                                }
                                // 删除一级产品按钮
                                IconButton(onClick = {
                                    configDataManager.removeProduct(context, product)
                                    products = configDataManager.getProducts()
                                }) {
                                    Icon(
                                        imageVector = Icons.Filled.Delete,
                                        contentDescription = "删除",
                                        tint = Color.Red
                                    )
                                }
                            }
                        }
                        
                        // 二级产品列表（仅在展开时显示）
                        if (isExpanded) {
                            Column(
                                modifier = Modifier.padding(start = 32.dp)
                            ) {
                                secondaryProducts.forEach { secondary ->
                                    Card(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 2.dp),
                                        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                                        colors = CardDefaults.cardColors(
                                            containerColor = Color(0xFFE8F5E9) // 浅绿色背景以区分二级产品
                                        )
                                    ) {
                                        Row(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(12.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Text(
                                                text = secondary,
                                                modifier = Modifier.weight(1f),
                                                style = androidx.compose.material3.MaterialTheme.typography.bodyMedium
                                            )
                                            
                                            IconButton(onClick = {
                                                configDataManager.removeSecondaryProduct(context, product, secondary)
                                                // 重新加载数据
                                                productsWithSecondaries = configDataManager.getProductsWithSecondaries()
                                            }) {
                                                Icon(
                                                    imageVector = Icons.Filled.Delete,
                                                    contentDescription = "删除",
                                                    tint = Color.Red
                                                )
                                            }
                                        }
                                    }
                                }
                                
                                // 添加二级产品的提示文本
                                if (secondaryProducts.isEmpty()) {
                                    Text(
                                        text = "暂无二级产品，点击上方+号添加",
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        style = androidx.compose.material3.MaterialTheme.typography.bodySmall,
                                        color = Color.Gray
                                    )
                                }
                            }
                        }
                    }
                }
                
                // 移除原有的长条形按钮，使用底部固定圆形按钮替代
            }
        }
        
        // 添加一级产品按钮，置于底部正中间
        FloatingActionButton(
            onClick = { showAddDialog = true },
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .padding(16.dp)
                .padding(bottom = 32.dp) // 增加距离屏幕底部的距离，与主页按钮一致
                .zIndex(2f)
                .size(56.dp), // 设置固定大小，确保是正圆形
            containerColor = Color.White // 设置为白色背景
        ) {
            Icon(
                imageVector = Icons.Filled.Add, 
                contentDescription = "添加产品",
                tint = Color(0xFF019883) // 设置图标为黑色以在白色背景上清晰显示
            )
        }
        
        // 添加一级产品对话框
        if (showAddDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showAddDialog = false },
                title = { Text("添加一级产品") },
                text = {
                    OutlinedTextField(
                        value = newProduct,
                        onValueChange = { newProduct = it },
                        label = { Text("一级产品名称") },
                        modifier = Modifier.fillMaxWidth()
                    )
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            if (newProduct.isNotBlank()) {
                                configDataManager.addProduct(context, newProduct)
                                products = configDataManager.getProducts()
                                productsWithSecondaries = configDataManager.getProductsWithSecondaries()
                                newProduct = ""
                                showAddDialog = false
                            }
                        }
                    ) {
                        Text("添加", color = Color(0xFF019883))
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showAddDialog = false }) {
                        Text("取消", color = Color(0xFF019883))
                    }
                }
            )
        }
        
        // 添加二级产品对话框
        if (showAddSecondaryDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showAddSecondaryDialog = false },
                title = { Text("添加二级产品") },
                text = {
                    Column {
                        Text(
                            text = "为 \"${selectedProduct}\" 添加二级产品",
                            modifier = Modifier.padding(bottom = 8.dp),
                            style = androidx.compose.material3.MaterialTheme.typography.bodyMedium
                        )
                        OutlinedTextField(
                            value = newSecondaryProduct,
                            onValueChange = { newSecondaryProduct = it },
                            label = { Text("二级产品名称") },
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            if (newSecondaryProduct.isNotBlank()) {
                                configDataManager.addSecondaryProduct(context, selectedProduct, newSecondaryProduct)
                                productsWithSecondaries = configDataManager.getProductsWithSecondaries()
                                newSecondaryProduct = ""
                                showAddSecondaryDialog = false
                            }
                        }
                    ) {
                        Text("添加", color = Color(0xFF019883))
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showAddSecondaryDialog = false }) {
                        Text("取消", color = Color(0xFF019883))
                    }
                }
            )
        }
    }
}

@Composable
fun ProductItem(
    product: String,
    onDelete: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        colors = CardDefaults.cardColors(
            containerColor = Color.White // 纯白背景
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp), // 缩小内边距
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = product,
                modifier = Modifier.weight(1f),
                style = androidx.compose.material3.MaterialTheme.typography.bodyLarge
            )
            IconButton(onClick = onDelete) {
                Icon(
                    imageVector = Icons.Filled.Delete,
                    contentDescription = "删除",
                    tint = Color.Red
                )
            }
        }
    }
}

@Composable
fun BackgroundImageManagementScreen(
    onNavigateBack: () -> Unit
) {
    val context = LocalContext.current
    val backgroundImageManager = BackgroundImageManager.getInstance()
    var showImagePicker by remember { mutableStateOf(false) }
    var showResultMessage by remember { mutableStateOf(false) }
    var resultMessage by remember { mutableStateOf("") }
    var backgroundImageExists by remember { 
        mutableStateOf(backgroundImageManager.isBackgroundImageExists(context)) 
    }
    var historyImagePaths by remember { 
        mutableStateOf(backgroundImageManager.getHistoryImagePaths(context)) 
    }
    // 添加状态变量用于触发背景图和历史图片重新加载
    var backgroundUpdateTrigger by remember { mutableStateOf(0) }
    var historyUpdateTrigger by remember { mutableStateOf(0) }
    // 添加确认对话框显示状态和要删除的历史图片路径
    var showConfirmDeleteDialog by remember { mutableStateOf(false) }
    var historyImagePathToDelete by remember { mutableStateOf("") }
    // 添加确认对话框显示状态
    var showConfirmDialog by remember { mutableStateOf(false) }
    // 用于临时存储选择的图片URI，以便进行裁剪
    var tempImageUri by remember { mutableStateOf<Uri?>(null) }
    
    // 注册uCrop裁剪结果处理器
    val cropImageLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        try {
            if (result.resultCode == android.app.Activity.RESULT_OK && result.data != null) {
                // 获取裁剪后的图片URI
                val croppedImageUri = UCrop.getOutput(result.data!!)
                if (croppedImageUri != null) {
                    // 保存裁剪后的图片
                    val success = backgroundImageManager.saveBackgroundImage(context, croppedImageUri)
                    if (success) {
                        resultMessage = "背景图片设置成功"
                        backgroundImageExists = true
                        // 更新历史图片列表
                        historyImagePaths = backgroundImageManager.getHistoryImagePaths(context)
                        // 触发背景图和历史图片重新加载
                        backgroundUpdateTrigger++
                        historyUpdateTrigger++
                        // 发送广播通知背景图已更新
                        val intent = Intent("com.xianyuwangyou.taizhangdengji.BACKGROUND_IMAGE_CHANGED")
                        intent.setPackage(context.packageName)
                        context.sendBroadcast(intent)
                    } else {
                        resultMessage = "背景图片设置失败，请重试"
                    }
                    showResultMessage = true
                } else {
                    resultMessage = "图片裁剪失败，请重试"
                    showResultMessage = true
                }
            } else if (result.resultCode == UCrop.RESULT_ERROR && result.data != null) {
                val cropError = UCrop.getError(result.data!!)
                resultMessage = "图片裁剪出错: ${cropError?.message ?: "未知错误"}"
                showResultMessage = true
            } else if (result.resultCode == android.app.Activity.RESULT_CANCELED) {
                resultMessage = "已取消图片选择"
                showResultMessage = true
            }
        } catch (e: Exception) {
            e.printStackTrace()
            resultMessage = "处理裁剪结果时发生错误: ${e.message}"
            showResultMessage = true
        }
        // 清除临时图片URI
        tempImageUri = null
    }
    
    // 启动图片裁剪功能
    fun startImageCropping(context: Context, sourceUri: Uri) {
        try {
            val destinationUri = Uri.fromFile(File(context.cacheDir, "cropped_background_image.jpg"))
            
            val options = UCrop.Options().apply {
                setCompressionFormat(android.graphics.Bitmap.CompressFormat.JPEG)
                setCompressionQuality(80)
                setToolbarTitle("裁剪背景图")
                setFreeStyleCropEnabled(false) // 禁用自由裁剪，强制使用固定比例
                // 移除颜色设置，让自定义主题生效
                // setToolbarColor(androidx.core.content.ContextCompat.getColor(context, androidx.appcompat.R.color.primary_material_dark))
                // setStatusBarColor(androidx.core.content.ContextCompat.getColor(context, androidx.appcompat.R.color.primary_dark_material_dark))
                // 设置蒙版颜色为透明，避免标题栏被灰色蒙版遮挡
                setDimmedLayerColor(ContextCompat.getColor(context, android.R.color.transparent))
                // 增加工具栏的顶部边距，使其与系统状态栏保持一定距离
                setToolbarWidgetColor(ContextCompat.getColor(context, android.R.color.black))
            }
            
            val uCrop = UCrop.of(sourceUri, destinationUri)
                .withOptions(options)
                .withAspectRatio(16f, 9f) // 固定宽高比为16:9
            
            cropImageLauncher.launch(uCrop.getIntent(context))
        } catch (e: Exception) {
            e.printStackTrace()
            resultMessage = "启动图片裁剪失败: ${e.message}"
            showResultMessage = true
        }
    }
    
    // 注册图片选择器
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        if (uri != null) {
            // 保存原始图片URI，用于裁剪
            tempImageUri = uri
            // 启动uCrop裁剪界面
            startImageCropping(context, uri)
        }
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.fillMaxSize()) {
            // 顶部工具栏
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White)
                    .padding(8.dp)
                    .padding(top = 24.dp) // 增加与屏幕顶端的距离
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                    Text(
                        text = "背景图管理",
                        style = androidx.compose.material3.MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }
            
            // 内容区域
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    text = "当前背景图",
                    style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(bottom = 16.dp)
                )
                
                // 显示当前背景图预览或默认图
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(200.dp)
                        .padding(bottom = 32.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current)
                            .data(
                                if (backgroundImageExists) {
                                    backgroundImageManager.getBackgroundImageUri(context) + "?t=$backgroundUpdateTrigger"
                                } else {
                                    "file:///android_asset/pic.png"
                                }
                            )
                            .crossfade(true)
                            .build(),
                        contentDescription = "背景图预览",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize()
                    )
                }
                
                // 历史背景图展示
                if (historyImagePaths.isNotEmpty()) {
                    Text(
                        text = "历史背景图",
                        style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
                        modifier = Modifier
                            .padding(bottom = 16.dp)
                            .align(Alignment.CenterHorizontally) // 从左对齐改为居中对齐
                    )
                    
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 32.dp)
                    ) {
                        items(historyImagePaths) { historyImagePath ->
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(100.dp)
                                    .padding(bottom = 8.dp),
                                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
                            ) {
                                Box(modifier = Modifier.fillMaxSize()) {
                                    // 历史背景图点击区域
                                    Box(
                                        modifier = Modifier
                                            .fillMaxSize()
                                            .clickable {
                                                // 交换当前背景图与选中的历史图片
                                                val success = backgroundImageManager.setHistoryImageAsBackground(context, historyImagePath)
                                                if (success) {
                                                    // 更新状态
                                                    backgroundImageExists = backgroundImageManager.isBackgroundImageExists(context)
                                                    // 更新历史图片列表
                                                    historyImagePaths = backgroundImageManager.getHistoryImagePaths(context)
                                                    // 触发背景图和历史图片重新加载
                                                    backgroundUpdateTrigger++
                                                    historyUpdateTrigger++
                                                    // 取消弹窗提醒
                                                    // resultMessage = "背景图已更新"
                                                    // showResultMessage = true
                                                    // 发送广播通知背景图已更新
                                                    val intent = Intent("com.xianyuwangyou.taizhangdengji.BACKGROUND_IMAGE_CHANGED")
                                                    intent.setPackage(context.packageName)
                                                    context.sendBroadcast(intent)
                                                } else {
                                                    resultMessage = "交换背景图失败"
                                                    showResultMessage = true
                                                }
                                            }
                                    ) {
                                        AsyncImage(
                                            model = ImageRequest.Builder(LocalContext.current)
                                                .data(backgroundImageManager.getHistoryImageUri(historyImagePath) + "?t=$historyUpdateTrigger")
                                                .crossfade(true)
                                                .build(),
                                            contentDescription = "历史背景图",
                                            contentScale = ContentScale.Crop,
                                            modifier = Modifier.fillMaxSize()
                                        )
                                    }
                                    
                                    // 删除按钮
                                    IconButton(
                                        onClick = {
                                            // 显示删除确认对话框
                                            historyImagePathToDelete = historyImagePath
                                            showConfirmDeleteDialog = true
                                        },
                                        modifier = Modifier
                                            .align(Alignment.CenterEnd)
                                            .padding(end = 8.dp)
                                    ) {
                                        Icon(
                                            imageVector = Icons.Filled.Delete,
                                            contentDescription = "删除历史背景图",
                                            tint = Color.Red
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 操作按钮
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 选择新图片按钮
                    androidx.compose.material3.Button(
                        onClick = {
                            imagePickerLauncher.launch("image/*")
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp, vertical = 8.dp)
                            .height(48.dp),
                        colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF019883)
                        )
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.Center
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Add,
                                contentDescription = "选择新图片",
                                tint = Color.White,
                                modifier = Modifier.size(18.dp)
                            )
                            Text(
                                text = "选择新图片",
                                color = Color.White,
                                modifier = Modifier.padding(start = 8.dp)
                            )
                        }
                    }
                    
                    // 恢复默认图片按钮（仅在自定义图片存在时显示）
                    if (backgroundImageExists) {
                        androidx.compose.material3.Button(
                            onClick = {
                                // 显示确认对话框
                                showConfirmDialog = true
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp, vertical = 8.dp)
                                .height(48.dp),
                            colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                                containerColor = Color.Red
                            )
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center
                            ) {
                                Icon(
                                    imageVector = Icons.Filled.Delete,
                                    contentDescription = "恢复默认图片",
                                    tint = Color.White,
                                    modifier = Modifier.size(18.dp)
                                )
                                Text(
                                    text = "恢复默认并删除历史背景图",
                                    color = Color.White,
                                    modifier = Modifier.padding(start = 8.dp)
                                )
                            }
                        }
                    }
                }
                
                // 删除确认对话框
                if (showConfirmDeleteDialog) {
                    androidx.compose.material3.AlertDialog(
                        onDismissRequest = { showConfirmDeleteDialog = false },
                        title = { Text("确认删除") },
                        text = { Text("确定要删除这张历史背景图吗？") },
                        confirmButton = {
                            TextButton(onClick = {
                                // 确认删除历史背景图
                                showConfirmDeleteDialog = false
                                val file = File(historyImagePathToDelete)
                                if (file.exists()) {
                                    file.delete()
                                    // 更新历史图片列表
                                    historyImagePaths = backgroundImageManager.getHistoryImagePaths(context)
                                    // 触发历史图片重新加载
                                    historyUpdateTrigger++
                                }
                                // 清空要删除的图片路径
                                historyImagePathToDelete = ""
                            }) {
                                Text("确定",color = Color.Red)
                            }
                        },
                        dismissButton = {
                            TextButton(onClick = {
                                // 取消删除
                                showConfirmDeleteDialog = false
                                // 清空要删除的图片路径
                                historyImagePathToDelete = ""
                            }) {
                                Text("取消",color = Color(0xFF019883))
                            }
                        }
                    )
                }
                
                // 结果提示对话框
                if (showResultMessage) {
                    androidx.compose.material3.AlertDialog(
                        onDismissRequest = { showResultMessage = false },
                        title = { Text("操作结果") },
                        text = { Text(resultMessage) },
                        confirmButton = {
                            TextButton(onClick = { showResultMessage = false }) {
                                Text("确定")
                            }
                        }
                    )
                }
                
                // 恢复默认图片确认对话框
                if (showConfirmDialog) {
                    androidx.compose.material3.AlertDialog(
                        onDismissRequest = { showConfirmDialog = false },
                        title = { Text("确认操作") },
                        text = { Text("将恢复为默认背景图并清空所有历史背景图，是否继续？") },
                        confirmButton = {
                            TextButton(onClick = {
                                // 确认恢复默认图片
                                showConfirmDialog = false
                                val file = File(backgroundImageManager.getBackgroundImagePath(context))
                                if (file.exists()) {
                                    file.delete()
                                    backgroundImageExists = false
                                    // 同时清除历史记录
                                    for (i in 0..2) {
                                        val historyFile = File(backgroundImageManager.getHistoryImagePath(context, i))
                                        if (historyFile.exists()) {
                                            historyFile.delete()
                                        }
                                    }
                                    // 更新历史图片列表
                                    historyImagePaths = backgroundImageManager.getHistoryImagePaths(context)
                                    // 触发背景图重新加载
                                    backgroundUpdateTrigger++
                                    // 触发历史图片重新加载
                                    historyUpdateTrigger++
                                    resultMessage = "已恢复为默认背景图"
                                    showResultMessage = true
                                    // 发送广播通知背景图已更新
                                    val intent = Intent("com.xianyuwangyou.taizhangdengji.BACKGROUND_IMAGE_CHANGED")
                                    intent.setPackage(context.packageName)
                                    context.sendBroadcast(intent)
                                }
                            }) {
                                Text("确定", color = Color.Red)
                            }
                        },
                        dismissButton = {
                            TextButton(onClick = {
                                // 取消操作
                                showConfirmDialog = false
                            }) {
                                Text("取消", color = Color(0xFF019883))
                            }
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun DataImportScreen(
    onNavigateBack: () -> Unit,
    onDataImported: () -> Unit
) {
    val context = LocalContext.current
    val dataManager = AccountDataManager.getInstance()
    var showImportResultDialog by remember { mutableStateOf(false) }
    var importResultMessage by remember { mutableStateOf("") }
    var isImporting by remember { mutableStateOf(false) }
    
    // 注册文件选择器
    val filePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        if (uri != null) {
            isImporting = true
            // 在后台线程中处理文件导入
            Thread {
                try {
                    val result = importLedgerData(context, uri)
                    (context as android.app.Activity).runOnUiThread {
                        importResultMessage = result
                        showImportResultDialog = true
                        isImporting = false
                        
                        // 如果导入成功，通知数据已更新
                        if (result.startsWith("成功导入")) {
                            onDataImported()
                        }
                    }
                } catch (e: Exception) {
                    (context as android.app.Activity).runOnUiThread {
                        importResultMessage = "导入失败: ${e.message}"
                        showImportResultDialog = true
                        isImporting = false
                    }
                }
            }.start()
        }
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        Column(modifier = Modifier.fillMaxSize()) {
            // 顶部工具栏
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.White)
                    .padding(8.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                    Text(
                        text = "导入台账",
                        style = androidx.compose.material3.MaterialTheme.typography.titleLarge,
                        modifier = Modifier.padding(start = 8.dp)
                    )
                }
            }
            
            // 内容区域
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "导入CSV格式台账数据",
                    style = androidx.compose.material3.MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(bottom = 32.dp)
                )
                
                // 说明文本
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 32.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text(
                            text = "CSV文件格式要求：",
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        Text(text = "• 第一行为标题行：ID,营销人,产品名称,数量,日期,备注")
                        Text(text = "• 后续每行为一条台账记录")
                        Text(text = "• 共6列数据，顺序不能颠倒")
                        Text(text = "• 日期格式：yyyy-MM-dd")
                        Text(text = "• 数量必须为整数")
                    }
                }
                
                // 导入按钮
                FloatingActionButton(
                    onClick = {
                        // 使用"*/*"提高文件选择器兼容性
                        filePickerLauncher.launch("*/*")
                    },
                    modifier = Modifier
                        .size(56.dp) // 设置固定大小，确保是正圆形
                        .padding(bottom = 16.dp),
                    containerColor = if (isImporting) Color.Gray else Color(0xFF6200EE)
                ) {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = "选择CSV文件",
                        tint = Color.White // 设置图标为白色以在彩色背景上清晰显示
                    )
                }
            }
        }
        
        // 导入结果对话框
        if (showImportResultDialog) {
            androidx.compose.material3.AlertDialog(
                onDismissRequest = { showImportResultDialog = false },
                title = { Text("操作结果") },
                text = { Text(importResultMessage) },
                confirmButton = {
                    TextButton(onClick = { showImportResultDialog = false }) {
                        Text("确定", color = Color(0xFF019883))
                    }
                }
            )
        }
    }
}

// 导出台账数据为CSV格式
fun exportLedgerData(context: Context, saveDirectory: String? = null, callback: (Boolean, String) -> Unit) {
    try {
        val dataManager = AccountDataManager.getInstance()
        val records = dataManager.getAccountRecords()
        
        if (records.isEmpty()) {
            callback(false, "没有台账数据可以导出")
            return
        }
        
        // 构建CSV内容
        val csvBuilder = StringBuilder()
        // 添加CSV头部（按照指定格式：ID，营销人，产品名称，二级产品名称，数量，日期，备注）
        csvBuilder.append("ID,营销人,产品名称,二级产品名称,数量,日期,备注\n")
        
        // 添加数据行
        for (record in records) {
            csvBuilder.append("${record.id},${record.marketer},${record.product},${record.secondaryProduct},${record.amount},${record.date},\"${record.notes}\"\n")
        }
        
        // 生成文件名（使用当前日期和时间）
        val dateFormat = java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault())
        val currentDate = dateFormat.format(java.util.Date())
        val fileName = "台账导出_$currentDate.csv"
        
        if (saveDirectory != null) {
            // 检查是否是URI格式的路径（来自DocumentFile）
            if (saveDirectory.startsWith("content://")) {
                // 使用DocumentFile API处理
                val treeUri = android.net.Uri.parse(saveDirectory)
                val documentFile = DocumentFile.fromTreeUri(context, treeUri)
                
                if (documentFile != null && documentFile.exists() && documentFile.isDirectory) {
                    // 创建文件
                    val csvFile = documentFile.createFile("text/csv", fileName)
                    if (csvFile != null) {
                        // 写入文件内容
                        context.contentResolver.openOutputStream(csvFile.uri)?.use { outputStream ->
                            outputStream.write(csvBuilder.toString().toByteArray(Charsets.UTF_8))
                        }
                        // 修改提示内容，显示更友好的路径信息
                        val displayPath = if (saveDirectory.contains("primary:")) {
                            val relativePath = saveDirectory.substringAfter("primary:")
                            "内部存储/$relativePath/$fileName"
                        } else {
                            // 对于其他类型的URI，显示基本的文件名
                            fileName
                        }
                        callback(true, "成功导出 ${records.size} 条记录到文件:\n$displayPath")
                        return
                    } else {
                        callback(false, "无法在所选目录中创建文件")
                        return
                    }
                } else {
                    callback(false, "所选目录无效")
                    return
                }
            } else {
                // 使用传统文件方式处理
                val directory = File(saveDirectory)
                if (!directory.exists()) {
                    directory.mkdirs()
                }
                
                // 写入文件
                val file = File(directory, fileName)
                file.writeText(csvBuilder.toString(), Charsets.UTF_8)
                
                callback(true, "成功导出 ${records.size} 条记录到文件:\n${file.absolutePath}")
                return
            }
        } else {
            // 使用默认目录
            val externalDir = when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                    if (Environment.isExternalStorageLegacy()) {
                        Environment.getExternalStorageDirectory()
                    } else {
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                    }
                }
                else -> {
                    Environment.getExternalStorageDirectory()
                }
            }
                    
            val dir = File(externalDir, "TaizhangDengji")
            if (!dir.exists()) {
                dir.mkdirs()
            }
            
            if (!externalDir.exists()) {
                externalDir.mkdirs()
            }
            
            // 写入文件
            val file = File(externalDir, fileName)
            file.writeText(csvBuilder.toString(), Charsets.UTF_8)
            
            callback(true, "成功导出 ${records.size} 条记录到文件:\n${file.absolutePath}")
        }
    } catch (e: Exception) {
        callback(false, "导出失败: ${e.message}")
    }
}

// 从CSV文件导入台账数据
fun importLedgerData(context: Context, fileUri: android.net.Uri): String {
    try {
        val inputStream = context.contentResolver.openInputStream(fileUri)
        var lineNumber = 0
        var importedCount = 0  // 成功导入的记录数
        var duplicateCount = 0  // 重复的记录数
        var errorCount = 0     // 导入失败的记录数
        val errorMessages = mutableListOf<String>()
        
        val dataManager = AccountDataManager.getInstance()
        val existingRecords = dataManager.getAccountRecords().toMutableList()
        
        inputStream?.bufferedReader()?.use { reader ->
            reader.lines().forEach { line ->
                lineNumber++
                // 跳过标题行
                if (lineNumber == 1) return@forEach
                
                try {
                    // 解析CSV行
                    val values = parseCsvLine(line)
                    if (values.size == 7) { // 修改为7列（移除了单位字段）
                        // 新格式：ID,营销人,产品名称,二级产品名称,数量,日期,备注
                        val id = values[0].toIntOrNull() ?: 0
                        val marketer = values[1]
                        val product = values[2]
                        val secondaryProduct = values[3] // 二级产品名称
                        // val unit = values[4] // 单位 - 已移除
                        val amount = values[4].toIntOrNull() ?: 0 // 数量列索引从5变为4
                        val date = values[5] // 日期列索引从6变为5
                        val notes = values[6].trim('"') // 备注列索引从7变为6
                        
                        val record = AccountRecord(
                            id = id,
                            marketer = marketer,
                            product = product,
                            secondaryProduct = secondaryProduct, // 二级产品名称
                            amount = amount,
                            date = date,
                            notes = notes
                        )
                        
                        // 检查是否已存在相同ID的记录
                        val existingIndex = existingRecords.indexOfFirst { it.id == record.id }
                        if (existingIndex >= 0) {
                            // 更新现有记录（重复内容）
                            existingRecords[existingIndex] = record
                            duplicateCount++
                        } else {
                            // 添加新记录（导入成功）
                            existingRecords.add(record)
                            importedCount++
                        }
                    } else if (values.size == 6) {
                        // 旧格式兼容：ID,营销人,产品名称,数量,日期,备注
                        val id = values[0].toIntOrNull() ?: 0
                        val marketer = values[1]
                        val product = values[2]
                        val amount = values[3].toIntOrNull() ?: 0
                        val date = values[4]
                        val notes = values[5].trim('"') // 去除可能的引号
                        
                        val record = AccountRecord(
                            id = id,
                            marketer = marketer,
                            product = product,
                            secondaryProduct = "", // 二级产品名称，导入旧格式时默认为空
                            amount = amount,
                            date = date,
                            notes = notes
                        )
                        
                        // 检查是否已存在相同ID的记录
                        val existingIndex = existingRecords.indexOfFirst { it.id == record.id }
                        if (existingIndex >= 0) {
                            // 更新现有记录（重复内容）
                            existingRecords[existingIndex] = record
                            duplicateCount++
                        } else {
                            // 添加新记录（导入成功）
                            existingRecords.add(record)
                            importedCount++
                        }
                    } else {
                        errorCount++
                        errorMessages.add("第${lineNumber}行列数不正确，期望8列（新格式）或6列（旧格式），实际${values.size}列")
                    }
                } catch (e: NumberFormatException) {
                    errorCount++
                    errorMessages.add("第${lineNumber}行数据格式错误: ${e.message}")
                } catch (e: Exception) {
                    errorCount++
                    errorMessages.add("第${lineNumber}行处理异常: ${e.message}")
                }
            }
        }
        
        // 保存更新后的数据
        dataManager.setAccountRecords(existingRecords)
        dataManager.saveAccountDataToFile(context)
        
        // 构建返回消息
        val resultMessage = "导入成功${importedCount}条，导入失败${errorCount}条，重复内容${duplicateCount}条。"
        
        // 如果有错误，添加详细错误信息
        if (errorMessages.isNotEmpty()) {
            val detailedMessage = resultMessage + "\n\n错误详情:\n" + errorMessages.take(5).joinToString("\n") // 只显示前5个错误
            return detailedMessage
        }
        
        return resultMessage
    } catch (e: Exception) {
        throw Exception("导入失败: ${e.message}")
    }
}

// 解析CSV行，处理引号和逗号
fun parseCsvLine(line: String): List<String> {
    val values = mutableListOf<String>()
    var currentValue = StringBuilder()
    var inQuotes = false
    
    for (char in line) {
        when {
            char == '"' -> {
                inQuotes = !inQuotes
            }
            char == ',' && !inQuotes -> {
                values.add(currentValue.toString().trim())
                currentValue = StringBuilder()
            }
            else -> {
                currentValue.append(char)
            }
        }
    }
    
    // 添加最后一个值
    values.add(currentValue.toString().trim())
    
    return values
}

// 从URI获取文件路径的辅助函数
fun getPathFromUri(context: Context, uri: Uri): String? {
    try {
        // 使用DocumentFile来处理目录URI，这是Android推荐的方式
        val documentFile = DocumentFile.fromTreeUri(context, uri)
        if (documentFile != null && documentFile.exists()) {
            // 返回URI本身作为标识，不尝试转换为文件路径
            // 在新版本Android中，直接使用URI比尝试转换为路径更可靠
            return uri.toString()
        }
        
        // 备用方案：尝试解析URI路径（适用于旧版本Android）
        val uriString = uri.toString()
        if (uriString.startsWith("content://com.android.externalstorage.documents/tree/")) {
            val pathPart = uriString.substringAfter("tree/")
            // 将%3A替换为:，然后处理路径
            val decodedPath = java.net.URLDecoder.decode(pathPart, "UTF-8")
            if (decodedPath.startsWith("primary:")) {
                val relativePath = decodedPath.substringAfter("primary:")
                // 使用更现代的方式获取外部存储目录
                val externalDir = when {
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                        // Android 11 (API 30) 及以上使用公共目录
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                    }
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                        // Android 10 (API 29) 检查是否使用传统存储
                        if (Environment.isExternalStorageLegacy()) {
                            Environment.getExternalStorageDirectory()
                        } else {
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                        }
                    }
                    else -> {
                        // Android 9 及以下版本
                        Environment.getExternalStorageDirectory()
                    }
                }
                return "${externalDir}/$relativePath"
            }
        }
        // 如果无法解析，返回默认路径
        val externalDir = when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                if (Environment.isExternalStorageLegacy()) {
                    Environment.getExternalStorageDirectory()
                } else {
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                }
            }
            else -> {
                Environment.getExternalStorageDirectory()
            }
        }
        return "$externalDir/TaizhangDengji"
    } catch (e: Exception) {
        e.printStackTrace()
        // 出现异常时返回默认路径
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                if (Environment.isExternalStorageLegacy()) {
                    Environment.getExternalStorageDirectory()
                } else {
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)
                }
            }
            else -> {
                Environment.getExternalStorageDirectory()
            }
        }.toString() + "/TaizhangDengji"
    }
}
